//
//  monthView.m
//  pb
//
//  Created by 千翼网络科技 on 2017/5/5.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "monthView.h"
#import "MonthTwoTableViewCell.h"
#import "MonthThreeTableViewCell.h"
#import "MonthOneTableViewCell.h"
#import "ICN_birthdayPickerView.h"
#import "UIButton+AddAction.h"
#import "planDetailsViewController.h"
#import "ToolAboutTime.h"
@implementation monthView

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
//        [self regeditCell];
        self.arrayOfData = [NSMutableArray array];
//        [self requestData];
        [self loginIs];
        
        [self creationView];
        
        self.backgroundColor = [UIColor greenColor];
    }
    
    return self;
}
- (void)creationView{
    

    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT- 49- 64);
    
    
    self.tableView.tableFooterView = [[UITableView alloc] initWithFrame:CGRectZero];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self addSubview:self.tableView];
    
//    self.arrOfDate = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六"].mutableCopy;
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MonthTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"MonthTwoTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MonthOneTableViewCell" bundle:nil] forCellReuseIdentifier:@"MonthOneTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MonthThreeTableViewCell" bundle:nil] forCellReuseIdentifier:@"MonthThreeTableViewCell"];
    
    
   
    
    
}
- (void)loginIs{
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Login_is
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       [self requestData];
                                       
                                   }else{
                                       
                                       [PublicFunction showAlert:nil message:returnData[@"msg"] duration:10.0f];
                                       
                                       loginViewController *loginVc = [[loginViewController alloc]init];
                                       
                                       [((SchedulingViewController *)self.vc) presentViewController:loginVc animated:YES completion:nil];
                                       
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

- (void)requestData{
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Month_Message
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       self.arrayOfData = [returnData objectForKey:@"data"];
                                       tempBirthdayStr = [returnData objectForKey:@"time"];
                                       yearStr = [returnData objectForKey:@"year"];
                                       monthStr = [returnData objectForKey:@"month"];
                                       [self.tableView reloadData];
                                       
                                       
                                   }else{
                                       
                                       [PublicFunction showAlert:nil message:@"没有行程" duration:5.0f];
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];

}


#pragma mark - ---------- Section的数量 ----------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

#pragma mark - ---------- 每个Section的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

#pragma mark - ---------- Cell的数量 ----------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1) {
    
        return 1;
    }else {
    
        return _dataArr.count;
        
    }
    
    
}

#pragma mark - ---------- 每个Cell的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        return screenScale(750);
        
    }else if (indexPath.section == 1) {
    
        return 45;
        
    }else {
        return 95;
        
    }
    
}
#pragma mark - ---------- 每个Cell的内容 ----------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        MonthOneTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MonthOneTableViewCell" forIndexPath:indexPath];
        
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        self.buttonTitle = [[UIButton alloc] init];
        [self.buttonTitle setTitleColor:[UIColor colorWithRed:119/255.0f green:119/255.0f blue:119/255.0f alpha:1] forState:UIControlStateNormal];
        [cell addSubview:self.buttonTitle];
        
        self.imagePic = [[UIImageView alloc] init];
        [cell addSubview:self.imagePic];
        self.imagePic.image = [UIImage imageNamed:@"select"];
        
        [self.imagePic mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).with.offset(23);
            make.left.equalTo(self.mas_centerX).with.offset(49);
            make.width.offset(8);
            make.height.offset(7);
            
        }];


        if (tempBirthdayStr == nil) {
            
            [self.buttonTitle setTitle:@"2017年5月" forState:UIControlStateNormal];
        }else {
        
            [self.buttonTitle setTitle:tempBirthdayStr forState:UIControlStateNormal];
        }
        
        [self.buttonTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.mas_centerX);
            make.height.offset(30);
            make.width.offset(100);
            make.top.equalTo(cell).with.offset(10);
            
        }];
        [self.buttonTitle addTarget:self action:@selector(setUserBirthday) forControlEvents:UIControlEventTouchUpInside];
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        CGFloat itemW     = DEF_SCREEN_WIDTH  / 7;
        CGFloat itemH     = DEF_SCREEN_WIDTH  / 7;

        // 2.weekday
        NSArray *array = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六"];
        self.weekBg = [[UIView alloc] init];
        //    weekBg.backgroundColor = [UIColor orangeColor];
        self.weekBg.frame = CGRectMake(0, itemH, DEF_SCREEN_WIDTH, itemH);
        [cell addSubview:self.weekBg];
        
        for (int i = 0; i < 7; i++) {
            UILabel *week = [[UILabel alloc] init];
            week.text     = array[i];
            week.layer.borderWidth = 1.0f;
            week.layer.borderColor =[UIColor whiteColor].CGColor;

            week.textColor = [UIColor colorWithRed:160 / 255.0f green:228 / 255.0f blue:235 / 255.0f alpha:1];
            week.font     = [UIFont systemFontOfSize:11];
            week.frame    = CGRectMake(itemW * i, 0, itemW, itemH);
            week.textAlignment   = NSTextAlignmentCenter;
            week.backgroundColor = [UIColor clearColor];
            [self.weekBg addSubview:week];
        }

        for (int i = 0; i < self.arrayOfData.count; i++) {
            
            int x = (i % 7) * itemW;
            int y = (i / 7) * itemH + CGRectGetMaxY(self.weekBg.frame);
            
            self.dayButton =[[UIButton alloc] init];
            [cell addSubview:self.dayButton];
            self.dayButton.frame = CGRectMake(x, y, itemW, itemH);
            self.dayButton.titleLabel.textAlignment = NSTextAlignmentCenter;
            self.dayButton.layer.cornerRadius = itemH / 2;
            self.dayButton.layer.masksToBounds = YES;
            
            
            self.dayButton.titleLabel.font = [UIFont systemFontOfSize:11];
//            self.dayButton.layer.borderWidth = 1.0f;
//            self.dayButton.layer.borderColor =[UIColor whiteColor].CGColor;
            UILabel *labelOfToday = [[UILabel alloc] init];
            [self.dayButton addSubview:labelOfToday];
            [labelOfToday mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.dayButton).with.offset(2);
                make.centerX.equalTo(self.dayButton.mas_centerX);
                make.width.offset(30);
                make.height.offset(10);
                
                
            }];
            labelOfToday.textAlignment = NSTextAlignmentCenter;
            
            labelOfToday.text = @"今日";
            labelOfToday.font = [UIFont systemFontOfSize:10];
            labelOfToday.textColor = [UIColor whiteColor];
            NSString *strDay = [NSString stringWithFormat:@"%@", [self.arrayOfData[i] objectForKey:@"isday"]];
            if ([strDay isEqualToString:@"0"]) {
                labelOfToday.hidden = YES;
            }else {
            
                labelOfToday.hidden = NO;
                
            }
            
            
            NSString *str =  [NSString stringWithFormat:@"%@", [self.arrayOfData[i] objectForKey:@"color"] ];
            if ([str isEqualToString:@"0"]) {
                
                [self.dayButton setTitleColor:getColor(@"cccccc") forState:UIControlStateNormal];
                self.dayButton.userInteractionEnabled = NO;
                
            }else {
                
                [self.dayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
//                [self.dayButton setTitleColor:getColor(@"cccccc") forState:UIControlStateSelected];
                
                 self.dayButton.tag = [[self.arrayOfData[i] objectForKey:@"time"] intValue];
                

                
                [self.dayButton addTarget:self action:@selector(logDate:) forControlEvents:UIControlEventTouchUpInside];
                
                self.dayButton.backgroundColor = getMainColor();
                
            }
            
            
            
            
            
            [self.dayButton setTitle:[self.arrayOfData[i] objectForKey:@"day"]forState:UIControlStateNormal];
            

            
            

            
        }

        
        return cell;
    }else if (indexPath.section == 1) {
        self.cellOf = [self.tableView dequeueReusableCellWithIdentifier:@"MonthTwoTableViewCell" forIndexPath:indexPath];
        
        
        self.cellOf.selectionStyle = UITableViewCellSelectionStyleNone;
        
 //       cell.xingCheng.text = [[ToolAboutTime getTimeStrByTimeSp:dataStr] stringByAppendingString:@"有行程"];
        
        
        return _cellOf;
        
    }else {
        MonthThreeTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MonthThreeTableViewCell" forIndexPath:indexPath];
        NSMutableDictionary *dic = self.dataArr[indexPath.row];
        NSString *strName1 = [dic objectForKey:@"name"];
        NSString *strName2 = [dic objectForKey:@"start_time"];
        NSString *strName3 = @"~";
        NSString *strName5 = @"  ";
        NSString *strName4 = [dic objectForKey:@"end_time"];
        
        cell.nameLabel.text = [[[[strName1 stringByAppendingString:strName5] stringByAppendingString:strName2] stringByAppendingString:strName3] stringByAppendingString:strName4];
        
        
        NSString *city1 = [dic objectForKey:@"start_city"];
        NSString *city2 = @"(";
        NSString *city3 = @")";
        NSString *city4 = [dic objectForKey:@"start_airport"];
        
        cell.start_city.text = [[[city1 stringByAppendingString:city2] stringByAppendingString:city4] stringByAppendingString:city3];
        
        NSString *endCity1 = [dic objectForKey:@"end_city"];
        NSString *endCity4 = [dic objectForKey:@"end_airport"];
        
        cell.end_city.text = [[[endCity1 stringByAppendingString:city2] stringByAppendingString:endCity4] stringByAppendingString:city3];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }

}
//日期选择
-(void)logDate:(UIButton *)dayBtn{

    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Login_is networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
        
            dataStr = [NSString stringWithFormat:@"%ld",(long)dayBtn.tag];
            
            _cellOf.xingCheng.text = [[ToolAboutTime getTimeStrByTimeSp:dataStr] stringByAppendingString:@" 有行程"];
            
            NSMutableDictionary *productParam=[[NSMutableDictionary alloc]init];
            
            [productParam setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
                                       
            
            [productParam setValue:dataStr forKey:@"time"];

            [[MNetworkHandler sharedInstance]conURL:MonthDay_Message networkType:NetWorkPOST params:productParam delegate:nil showHUD:NO successBlock:^(id returnData) {
                
                if ([[returnData objectForKey:@"code"]intValue]==1) {
                                                                          
                    
                    self.dataArr = [returnData objectForKey:@"data"];
                                                                          
                    
                    [self.tableView reloadData];
                                                                          
                    
                }else{
                                                                          
                    
                    [PublicFunction showAlert:nil message:@"没有行程" duration:5.0f];
                                                                          
                    
                }
                
            } failureBlock:^(NSError *error) {
                
                NSLog(@"%@",error);
                
                [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                
            }];
            
            
            NSLog(@"aaaAAAAAAAAAAAAAAAAA");

                                       
                                       
                                       
            
        }else{
                                       
            
            [PublicFunction showAlert:nil message:returnData[@"msg"] duration:10.0f];
                                       
            
            loginViewController *loginVc = [[loginViewController alloc]init];
                                       
            
            [((SchedulingViewController *)self.vc) presentViewController:loginVc animated:YES completion:nil];
                                       
                                       
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        
    }];

    
    
}




#pragma mark - ---------- 每个Cell的点击事件 ----------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        planDetailsViewController *settingVC=[[planDetailsViewController alloc]init];
        settingVC.hidesBottomBarWhenPushed=YES;
        
        settingVC.idStr = [self.dataArr[indexPath.row] objectForKey:@"id"];
        
        
        [((SchedulingViewController *)self.vc).navigationController pushViewController:settingVC animated:YES];
    }
    
    
    
}
- (void)setGrayView {
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    grayView.backgroundColor = [UIColor blackColor];
    grayView.alpha = 0.5;
//    [self addSubview:grayView];
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
}
#pragma mark - ---------- 日期选择 ----------
- (void)setUserBirthday {
//    [self setGrayView];
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
     grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
  //  [self addSubview:grayView];
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
    _birthdayView = XIB(ICN_birthdayPickerView);
    _birthdayView.delegate = self;
    self.birthdayView.frame = CGRectMake(0, DEF_SCREEN_HEIGHT-163, DEF_SCREEN_WIDTH, 163);
    [self.birthdayView.cancelButton addAction:^(NSInteger tag) {
        [grayView removeFromSuperview];
    }];

    NSInteger year = [yearStr intValue] - 2017;
    NSInteger month = [monthStr intValue] - 1;
    
    [self.birthdayView.birthdayPickerView selectRow:month inComponent:1 animated:YES];
    [self.birthdayView.birthdayPickerView selectRow:year inComponent:0 animated:YES];
    
    [grayView addSubview:self.birthdayView];
    [self.birthdayView.saveBirthdayButton addTarget:self action:@selector(birthdayChoose) forControlEvents:UIControlEventTouchUpInside];
    
}
//确认选择年月
- (void)birthdayChoose {
    
    
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Login_is networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        if ([[returnData objectForKey:@"code"]intValue]==1) {
            
            
            NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
            [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
            if ([tempBirthdayStr isEqualToString:@""]) {
                [productParams setValue:@"2017年1月" forKey:@"time"];
            }else {
                [productParams setValue:tempBirthdayStr forKey:@"time"];
                
            }
           
            [[MNetworkHandler sharedInstance]conURL:Month_Message networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
                
                if ([[returnData objectForKey:@"code"]intValue]==1) {
                                               
                    
                    self.arrayOfData = [returnData objectForKey:@"data"];
                                               
                    
                    [self.dataArr removeAllObjects];
                                               
                    
                    _cellOf.xingCheng.text = @"有行程";
                    yearStr = [returnData objectForKey:@"year"];
                    monthStr = [returnData objectForKey:@"month"];
                    
                    
                    [self.tableView reloadData];
                                               
                                               
                    
                }else{
                                               
                    
                    [PublicFunction showAlert:nil message:@"没有行程" duration:5.0f];
                                               
                    
                }
                
            } failureBlock:^(NSError *error) {
                
                NSLog(@"%@",error);
                
                [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                
            }];
            
            
            [self.buttonTitle setTitle:tempBirthdayStr forState:UIControlStateNormal];
            
            
            NSLog(@"QQQQQQQQQQQQQ%@", tempBirthdayStr);
            
            
            
            
            
        }else{
            
            
            [PublicFunction showAlert:nil message:returnData[@"msg"] duration:10.0f];
            
            
            loginViewController *loginVc = [[loginViewController alloc]init];
            
            
            [((SchedulingViewController *)self.vc) presentViewController:loginVc animated:YES completion:nil];
            
            
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        
    }];

   
  
    [grayView removeFromSuperview];
}
//代理
- (void)getBirthdayYear:(NSString *)year andMonth:(NSString *)month {
    if (year == NULL) {
        year = [yearStr stringByAppendingString:@"年"];
    }
    if (month == NULL) {
        month = [monthStr stringByAppendingString:@"月"];
    }
    tempBirthdayStr = [NSString stringWithFormat:@"%@%@",year,month];
    
    
}



- (void)dismissContactView {
    [grayView removeFromSuperview];
}



@end
